# 定义进程终止函数
kill_old_process() {
  local jar_name=$1
  local pid_list=$(pgrep -f "java.*$jar_name")

  if [ -n "$pid_list" ]; then
    echo "Found existing process(es) for $jar_name: $pid_list"

    # 优雅终止
    kill $pid_list
    echo "Sent SIGTERM to process(es), waiting for termination..."

    # 等待进程退出
    local timeout=0
    while kill -0 $pid_list 2>/dev/null && [ $timeout -lt $KILL_TIMEOUT ]; do
      sleep 1
      ((timeout++))
    done

    # 强制终止未退出的进程
    if kill -0 $pid_list 2>/dev/null; then
      echo "Force killing process(es)..."
      kill -9 $pid_list
    fi

    # 二次确认
    if pgrep -f "java.*$jar_name" >/dev/null; then
      echo "Error: Failed to kill process for $jar_name!" >&2
      return 1
    fi
  fi
  return 0
}